package ru.nsu.ccfit.kalah.game;

import java.util.ArrayList;
import java.util.List;

public class ObjectPool<E> {
    public interface Creator<E> {
        E newInstance();
    }

    private Creator<E> creator;

    public ObjectPool(Creator<E> creator) {
        this.creator = creator;
    }

    private List<E> pool;
    public void put(E element) {
        if(pool == null) {
            pool = new ArrayList<E>();
        }

        pool.add(element);
    }

    public E get() {
        if(pool != null && !pool.isEmpty()) {
            return pool.remove(pool.size()-1);
        }

        return creator.newInstance();
    }
}
